// 'use strict'
import Vue from 'vue'
import {
	app,
	protocol,
	BrowserWindow,
	ipcMain,
	Menu,
	Tray
} from 'electron'
import {
	createProtocol
} from 'vue-cli-plugin-electron-builder/lib'
import installExtension, {
	VUEJS_DEVTOOLS
} from 'electron-devtools-installer'
import {
	handleUpdate
} from "./handleUpdate.js" // 更新
const isDevelopment = process.env.NODE_ENV !== 'production'
const path = require('path')

// Scheme must be registered before the app is ready   在应用程序准备好之前，Scheme必须被注册
protocol.registerSchemesAsPrivileged([{
	scheme: 'app',
	privileges: {
		secure: true,
		standard: true
	}
}])
let win = null;
let tray = null; // 系统托盘
let timer = null; // 闪烁
let ishide = false; // 检测是否进入托盘 
async function createWindow() {
	// Create the browser window.
	win = new BrowserWindow({
		width: 500,
		height: 750,
		// frame: false, // 去掉窗口边框
		// titleBarStyle: "hidden", // 隐藏标题栏
		icon: path.join(__static, "../public/icon.png"),
		webPreferences: {
			webSecurity: false, // //关闭web权限检查，允许跨域
			nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
			contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
			// disableBlinkFeatures:"Accelerated2dCanvas"
		}
	})
	win.show();
	if (process.env.WEBPACK_DEV_SERVER_URL) {
		// Load the url of the dev server if in development mode
		await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
		if (!process.env.IS_TEST) win.webContents.openDevTools() //  调试窗口
	} else { // 打包环境
		createProtocol('app');
		Menu.setApplicationMenu(null) //隐藏菜单栏（顶部调试功能；打开则隐藏）
		// Load the index.html when not in development
		win.loadURL('app://./index.html')
	}

	//启动白屏闪烁解决
	win.once('ready-to-show', () => {
		win.show();
		//检查更新（.exe .vml）
		handleUpdate(win, "https://www.hnytw.cn/pc/")
	});
	/*----------------系统托盘-start*/
	app.whenReady().then(() => {
		if (process.env.WEBPACK_DEV_SERVER_URL) { // 开发版本
			tray = new Tray(path.join(__dirname, "../public/icon.ico"));
		} else {  // exe线上 发布版本
			tray = new Tray(
				path.join(path.dirname(app.getPath("exe")), "resources/app/icon.ico")
			);
		}
		const contextMenu = Menu.buildFromTemplate([{
			label: "退出",
			click() {
				app.quit();
			},
		},]);
		tray.setToolTip("豫图网");
		tray.setContextMenu(contextMenu);
		tray.on("click", (event, bounds, position) => {
			clearInterval(timer);
			timer = null;
			ishide = false;
			star()
			win.show();
		});
	});

	// 点击关闭按钮让应用保存在托盘
	win.on("close", (e) => {
		if (!win.isFocused()) {
			win = null;
		} else {
			// 阻止窗口的关闭事件
			e.preventDefault();
			clearInterval(timer);
			timer = null;
			ishide = true;
			win.webContents.send('showWin', false)
			win.hide(); // win.close()
		}
	});
	/*----------系统托盘-end*/
	/*窗口最小化和托盘消息已读未读处理-start*/
	win.on('minimize', () => {
		win.webContents.send('showWin', false)
	});
	win.on('focus', () => {
		win.webContents.send('showWin', true)
	});
	/*窗口最小化和托盘消息已读未读处理-end*/
}
/*闪烁-start*/
function star() {
	if (ishide) {
		win.webContents.send('play-notification-sound');
		if (!timer) {
			var count = 0;
			timer = setInterval(function() {
				if (count++ % 2 == 0) {
					if (process.env.WEBPACK_DEV_SERVER_URL) {
						tray.setImage(path.join(__dirname, "../public/icon.ico"));
					} else {
						tray.setImage(
							path.join(
								path.dirname(app.getPath("exe")),
								"resources/app/icon.ico"
							)
						);
					}
				} else {
					if (process.env.WEBPACK_DEV_SERVER_URL) {
						tray.setImage(path.join(__dirname, "../public/favicon.ico"));
					} else {
						tray.setImage(
							path.join(
								path.dirname(app.getPath("exe")),
								"resources/app/favicon.ico"
							)
						);
					}
				}
			}, 400);
		}
	} else {
		if (process.env.WEBPACK_DEV_SERVER_URL) {
			tray.setImage(path.join(__dirname, "../public/icon.ico"));
		} else {
			tray.setImage(
				path.join(path.dirname(app.getPath("exe")), "resources/app/icon.ico")
			);
		}
	}
}
// add fun
app.setName('豫图网');
ipcMain.on('maxsize', async () => {
	win.setSize(1300, 750);
	win.setMinimumSize(1000, 750)
});
ipcMain.on('center', async () => {
	win.center()
});
ipcMain.on('minsize', async () => {
	win.setSize(500, 750);
	win.setMinimumSize(500, 750)
	win.center()
});
ipcMain.on('flashFrame', async () => { // 启动或停止闪烁窗口, 以吸引用户的注意。
	win.once('focus', () => win.flashFrame(false))
	win.webContents.send('play-notification-sound');  // app.vue监听；来消息提醒
	win.flashFrame(true)
});

ipcMain.on('starfun', async () => { // 启动或停止闪烁窗口, 以吸引用户的注意。
	star();
});

// Quit when all windows are closed.
app.on('window-all-closed', () => {
	// On macOS it is common for applications and their menu bar 在macOS上，应用程序和它们的菜单栏是很常见的
	// to stay active until the user quits explicitly with Cmd + Q  保持活动状态，直到用户使用Cmd + Q显式退出
	if (process.platform !== 'darwin') {
		app.quit()
	}
})

/*------------------语音子窗口-start*/
let callWindow = null; // 子窗口
let time1 = null
let time2 = null
let time3 = null
ipcMain.on("open-call-window", () => {
	if (callWindow) {
		callWindow.focus();
		return;
	}
	callWindow = new BrowserWindow({
		parent: win,
		width: 350,
		height: 600,
		minWidth: 350,
		minHeight: 600,
		maxWidth: 350,
		maxHeight: 600,
		icon: path.join(__static, "../public/icon.png"),
		frame: false, // 去掉窗口边框
		titleBarStyle: "hidden", // 隐藏标题栏
		/*设置无边框之后无法拖动解决办法   设置可拖动位置样式，即可拖动
		style="-webkit-app-region: drag;"
		*/
		webPreferences: {
			nodeIntegration: true,
			contextIsolation: false,
		},
	});
	callWindow.setTitle("豫图网");

	if (process.env.WEBPACK_DEV_SERVER_URL) {  // 调试
		callWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL + "/#/voice");
		callWindow.webContents.openDevTools() //  调试窗口
	} else {  // 打包环境
		callWindow.loadURL("app://./index.html" + "#/voice");
	}
	// callWindow.webContents.openDevTools()  // 调试模式
	callWindow.on("closed", () => {
		callWindow = null;
	});
});
ipcMain.on("childClose", async () => { // 关闭
	if (callWindow) {
		if (time1) {
			clearTimeout(time1)
			time1 = null
		}
		if (time2) {
			clearTimeout(time2)
			time2 = null
		}
		if (time3) {
			clearTimeout(time3)
			time3 = null
		}
		callWindow.destroy();
		callWindow = null;
		// callWindow.close();
	}
})
ipcMain.on("child-mini", async () => { // 缩小
	callWindow.minimize()
})
/*
发送地点：
1、\src\components\tabnav  
2、\src\components\chat\socket
*/
ipcMain.on("appendMessage", (event, data) => { // 推送数据
	if (callWindow) {
		time1 = setTimeout(() => {
			callWindow.webContents.send('appendMessagedata', data)
		}, 600)
	}
})
ipcMain.on("statustype", (event, data) => { // 1拨打 2 接听
	if (callWindow) {
		time2 = setTimeout(() => {
			callWindow.webContents.send('statustypedata', data)
		}, 600)
	}
})
ipcMain.on("infodataacitem", (event, data) => { // 拨打时对方数据
	if (callWindow) {
		time3 = setTimeout(() => {
			callWindow.webContents.send('infodataacitemdata', data)
		}, 600)
	}
})
ipcMain.on("chatsend", (event, data) => { // 将datas数据返回到聊天页面
	win.webContents.send('chatsenddata', data)
})

/*语音子窗口-end*/

app.on('activate', () => {
	// On macOS it's common to re-create a window in the app when the  在macOS上，通常会在应用程序中重新创建一个窗口
	// dock icon is clicked and there are no other windows open.  单击dock图标，没有其他窗口打开。
	if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished  这个方法将在Electron完成时被调用
// initialization and is ready to create browser windows.   初始化，并准备创建浏览器窗口。
// Some APIs can only be used after this event occurs.    某些api只能在此事件发生后使用。
app.on('ready', async () => {
	// if (isDevelopment && !process.env.IS_TEST) {
	//   // Install Vue Devtools
	//   try {
	//     await installExtension(VUEJS_DEVTOOLS)
	//   } catch (e) {
	//     console.error('Vue Devtools failed to install:', e.toString())
	//   }
	// }
	createWindow();
})

// Exit cleanly on request from parent process in development mode.  在开发模式下，根据父进程的请求干净地退出。
if (isDevelopment) {
	if (process.platform === 'win32') {
		process.on('message', (data) => {
			if (data === 'graceful-exit') {
				app.quit()
			}
		})
	} else {
		process.on('SIGTERM', () => {
			app.quit()
		})
	}
}

/*其他方法
1、使用resize事件来监听窗口大小的变化。
callWindow.on('resize', () => {
  const { width, height } = mainWindow.getBounds();
  console.log(`窗口大小变为：${width}x${height}`);
});
*/ 